//
//  TeamViewController.m
//  InviteJob
//
//  Created by LangLang on 17/11/1.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "TeamViewController.h"

@interface TeamViewController ()<TZImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *viewCompany;
@property (nonatomic,strong) SZTextView *textView;
@property (weak, nonatomic) IBOutlet UITextField *txName;
@property (weak, nonatomic) IBOutlet UITextField *txtIdCard;

@property (weak, nonatomic) IBOutlet UIImageView *iconIdCard;

@property (nonatomic,strong) NSArray *idCardArr;



@end

@implementation TeamViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    self.automaticallyAdjustsScrollViewInsets = NO;
    // 获取数据
    [self getDataItem];
    [self layout];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotificiation:) name:@"buttonTeam" object:@"buttonTeam"];
    
    
}
- (void)receiveNotificiation:(NSNotification*)sender{
    
    NSLog(@"过来了是真的");
    [self updata];
    
}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"buttonTeam" object:@"buttonTeam"];
    
}

- (void)layout{
    _scrollView.contentSize = CGSizeMake(WIDTH, 570);
    
    [_iconIdCard setUserInteractionEnabled:YES];
    [_iconIdCard addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickCategory:)]];
    
    _textView = [SZTextView new];
    _textView.font = [UIFont systemFontOfSize:14];
    _textView.placeholder = @"请输入团队描述";
    [_viewCompany addSubview:_textView];
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_viewCompany);
    }];
}
-(void)clickCategory:(UITapGestureRecognizer *)gestureRecognizer
{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos,NSArray *assets,BOOL isSelectOriginalPhoto){
        _idCardArr = photos;
        _iconIdCard.image = photos[0];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}


#pragma mark --数据上传

-(void)updata{
    
    
    if (_txName.text.length==0) {
        SHuiMBhudTextTimeStr(@"请填写你的姓名");
        return;
    }
    
    if (![SHJudgeTools validateIdentityCard:_txtIdCard.text]) {
        SHuiMBhudTextTimeStr(@"请填写正确的身份证号");
        return;
    }
    
    if (_textView.text.length==0) {
        SHuiMBhudTextTimeStr(@"请输入团队描述");
        return;
    }
    
    NSString *strUrl = [NSString stringWithFormat:post_completeInfo_api];
    
    isUser
    NSDictionary *parameter = @{@"user_id":user.user_id,
                                @"token":user.token,
                                @"type":@"team",
                                @"username":_txName.text,
                                @"id_card":_txtIdCard.text,
                                @"content":_textView.text};
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/html",@"application/json",@"text/javascript",nil];
    manager.requestSerializer.timeoutInterval = 10;
    [MBProgressHUD showMessag:@"保存中..." withDelay:0 toView:self. view withMode:MBProgressHUDModeIndeterminate hideWithDelay:0];
    [manager POST:strUrl parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
       
        
        if (_idCardArr.count!=0) {
            NSData *imageData = [self compressOriginalImage:_idCardArr[0] toMaxDataSizeKBytes:200];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.png",str];
            [formData appendPartWithFileData:imageData
                                        name:@"img_str"
                                    fileName:fileName
                                    mimeType:@"image/png"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary * data = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",data);
        SHuiMBHidleYes
        if ([data[@"code"] intValue] == 200) {
            SHuiMBhudTextTimeStr(@"认证提交成功，正在审核中");
            
        }else{
            SHuiMBhudTextTimeStr(data[@"mark"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        SHuiMBHidleYes
        SHuiMBhudTextTimeStr(@"网络异常");
    }];
    
}

//图片压缩到指定大小
/**
 *  压缩图片到指定文件大小
 *
 *  @param image 目标图片
 *  @param size  目标大小（最大值）
 *
 *  @return 返回的图片文件
 */
- (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{
    NSData * data = UIImageJPEGRepresentation(image, 1.0);
    CGFloat dataKBytes = data.length/1000.0;
    CGFloat maxQuality = 0.9f;
    CGFloat lastData = dataKBytes;
    while (dataKBytes > size && maxQuality > 0.01f) {
        maxQuality = maxQuality - 0.01f;
        data = UIImageJPEGRepresentation(image, maxQuality);
        dataKBytes = data.length / 1000.0;
        if (lastData == dataKBytes) {
            break;
        }else{
            lastData = dataKBytes;
        }
    }
    return data;
}


#pragma mark --  获取数据

-(void)getDataItem{
    isUser
    NSString *strUrl = [NSString stringWithFormat:post_authen_getInfo_api];
    NSDictionary *parameter = @{@"user_id":user.user_id, @"token":user.token};
    [PostNetWorking postNetWorkingStr:strUrl andparameters:parameter Success:^(id responseObject) {
        int code = [responseObject[@"code"]intValue];
        switch (code) {
            case 200:
            {
                
                if ([responseObject[@"datas"][@"type"] isEqualToString:@"team"]) {
                    [_iconIdCard sd_setImageWithURL:[NSURL URLWithString:responseObject[@"datas"][@"license"]]];
                    _txName.text = responseObject[@"datas"][@"username"];
                    _textView.text = responseObject[@"datas"][@"content"];
                    _txtIdCard.text = responseObject[@"datas"][@"id_card"];
                }else{
                    return ;
                }
                
                
            }
                break;
            case 210:
            {
                //逻辑错误
                [MBProgressHUD showMessag:responseObject[@"mark"] withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
            }
                break;
            case 220:
            {
                //token过期
                [MBProgressHUD showMessag:@"登录状态已过期，请重新登录" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
            }
            default:
                break;
        }
        
    } failed:^(NSError *error) {
        [MBProgressHUD showMessag:@"网络错误" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
    }];
}



@end
